package com.toro.client.handler;

import com.toro.client.ChatClient;
import com.toro.message.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ClassName: MyChannelInboundHandlerAdapter
 * @Description:
 * @Author: ToroLHZ
 * @Date: 2023/12/12 19:17
 */
@Slf4j
public class MyChannelInboundHandlerAdapter extends ChannelInboundHandlerAdapter {
    private final AtomicBoolean LOGIN;
    private final CountDownLatch WAIT_FORLOGIN;

    public MyChannelInboundHandlerAdapter(AtomicBoolean LOGIN, CountDownLatch WAIT_FORLOGIN) {
        this.LOGIN = LOGIN;
        this.WAIT_FORLOGIN = WAIT_FORLOGIN;
    }
    //接收响应事件

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("{}", msg);

        //登陆
        if (msg instanceof LoginResponseMessage) {
            log.info("登录响应:{}", msg);
            LoginResponseMessage responseMessage = (LoginResponseMessage) msg;
            if (responseMessage.isSuccess()) {
                this.LOGIN.set(true);
                System.out.println("登陆成功");
            }
            //唤醒system in线程
            this.WAIT_FORLOGIN.countDown();
        }
        //接收消息
        else if (msg instanceof ChatResponseMessage) {
            log.info("消息响应:{}", msg);
            ChatResponseMessage responseMessage = (ChatResponseMessage) msg;
            if (responseMessage.isSuccess()) {
                if (responseMessage.getFrom() != null) {
                    System.out.println(responseMessage.getFrom() + "===>" + responseMessage.getContent());
                } else {
                    System.out.println(responseMessage.getReason());
                }

            } else {
                System.out.println("发送失败： " + responseMessage.getReason());
            }
        }
        //成员群消息
        else if (msg instanceof GroupChatResponseMessage) {
            GroupChatResponseMessage groupChatResponseMessage = (GroupChatResponseMessage) msg;
            if (groupChatResponseMessage.isSuccess()) {
                if (groupChatResponseMessage.getReason() != null) {
                    System.out.println(groupChatResponseMessage.getReason());
                }
                if (groupChatResponseMessage.getFrom() != null) {
                    System.out.println("来自群：" + groupChatResponseMessage.getGroupName() + "->" + groupChatResponseMessage.getFrom() + "发来的消息：" + groupChatResponseMessage.getContent());
                }

            } else {
                System.out.println(groupChatResponseMessage.getReason());
            }
        }
        //创建群后成员群消息 创建组消息
        else if (msg instanceof GroupCreateResponseMessage) {
            GroupCreateResponseMessage groupCreateResponseMessage = (GroupCreateResponseMessage) msg;
            if (groupCreateResponseMessage.isSuccess()) {
                System.out.println(groupCreateResponseMessage.getReason());
            }
        } else if (msg instanceof GroupMembersResponseMessage) {
            GroupMembersResponseMessage groupMembersResponseMessage = (GroupMembersResponseMessage) msg;
            List<String> members = groupMembersResponseMessage.getMembers();
            if (members != null) {
                System.out.print("群: " + groupMembersResponseMessage.getGroupName());
                System.out.print(" 成员有：");
                for (String member : members) {
                    System.out.print(member + " ");
                }
            }
        } else if (msg instanceof GroupJoinResponseMessage) {
            GroupJoinResponseMessage joinResponseMessage = (GroupJoinResponseMessage) msg;
            if (joinResponseMessage.isSuccess()) {
                if (joinResponseMessage.getReason() != null) {
                    System.out.println(joinResponseMessage.getReason());
                }
            } else {
                System.out.println("加群失败：" + joinResponseMessage.getReason());
            }
        } else if (msg instanceof GroupQuitResponseMessage) {
            GroupQuitResponseMessage quitResponseMessage = (GroupQuitResponseMessage) msg;
            if (quitResponseMessage.isSuccess()) {
                if (quitResponseMessage.getReason() != null) {
                    System.out.println(quitResponseMessage.getReason());
                }
            } else {
                System.out.println("退群失败：" + quitResponseMessage.getReason());
            }
        } else {
            log.debug("msg:{}", msg);
        }

    }

    //连接建立好后触发active事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //负责接收用户输入，复制向服务器发送消息
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入用户名:");
            String username = scanner.nextLine();
            System.out.print("请输入密码:");
            String password = scanner.nextLine();
            LoginRequestMessage message = new LoginRequestMessage(username, password);
            log.info("登录请求{}", message);
            ctx.writeAndFlush(message);
            System.out.println("等待后续操作...");
            try {
                this.WAIT_FORLOGIN.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //登陆失败
            if (!this.LOGIN.get()) {
                ctx.channel().close();
                return;
            }
            //登陆成功
            while (true) {
                System.out.println("==================================");
                System.out.println("send [username] [content]");
                System.out.println("gsend [group name] [content]");
                System.out.println("gcreate [group name] [m1,m2,m3...]");
                System.out.println("gmembers [group name]");
                System.out.println("gjoin [group name]");
                System.out.println("gquit [group name]");
                System.out.println("quit");
                System.out.println("==================================");
                String command = scanner.nextLine();
                String[] s = command.split(" ");
                log.info("输入的消息: {},{}", command, s);
                switch (s[0]) {
                    case "send":
                        ChatRequestMessage chatRequestMessage = new ChatRequestMessage(username, s[1], s[2]);
                        ctx.writeAndFlush(chatRequestMessage);
                        log.info("发送消息请求：{}", chatRequestMessage);
                        break;
                    case "gsend":
                        GroupChatRequestMessage groupChatRequestMessage = new GroupChatRequestMessage(username, s[1], s[2]);
                        ctx.writeAndFlush(groupChatRequestMessage);
                        log.info("发送群消息请求：{}", groupChatRequestMessage);
                        break;
                    case "gcreate":
                        ArrayList<String> list = new ArrayList<String>(Arrays.asList(s[2].split(",")));
                        list.add(username);
                        GroupCreateRequestMessage groupCreateRequestMessage = new GroupCreateRequestMessage(s[1], list, username);
                        ctx.writeAndFlush(groupCreateRequestMessage);
                        log.info("创建群请求：{}", groupCreateRequestMessage);
                        break;
                    case "gmembers":
                        GroupMembersRequestMessage groupMembersRequestMessage = new GroupMembersRequestMessage(s[1]);
                        ctx.writeAndFlush(groupMembersRequestMessage);
                        log.info("获取群成员请求：{}", groupMembersRequestMessage);
                        break;
                    case "gjoin":
                        GroupJoinRequestMessage groupJoinRequestMessage = new GroupJoinRequestMessage(username, s[1]);
                        ctx.writeAndFlush(groupJoinRequestMessage);
                        log.info("加入群请求：{}", groupJoinRequestMessage);
                        break;
                    case "gquit":
                        GroupQuitRequestMessage groupQuitRequestMessage = new GroupQuitRequestMessage(username, s[1]);
                        ctx.writeAndFlush(groupQuitRequestMessage);
                        log.info("退出群请求：{}", groupQuitRequestMessage);
                        break;
                    case "quit":
                        ctx.channel().close();
                        log.info("退出登录");
                        return;
                    default:
//                        System.out.println("======="+s[0]);
                        break;
                }
                try {
                    System.in.read();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "system in").start();
    }

    //在连接断开时触发
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接已经断开，按任意键退出..");
        log.info("连接已经断开，按任意键退出..");
        super.channelInactive(ctx);
    }

    //在出现异常时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("连接已经断开，按任意键退出..");
        log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
        super.exceptionCaught(ctx, cause);
    }
}
